package com.netease.nim.uikit.business.session.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.netease.nim.uikit.business.util.Des3Util;
import com.netease.nim.uikit.business.util.bars.StatusBarUtil;
import com.netease.nim.uikit.common.ToastHelper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netease.nim.uikit.R;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.api.model.contact.ContactChangedObserver;
import com.netease.nim.uikit.api.model.main.OnlineStateChangeObserver;
import com.netease.nim.uikit.api.model.session.SessionCustomization;
import com.netease.nim.uikit.api.model.user.UserInfoObserver;
import com.netease.nim.uikit.api.wrapper.NimToolBarOptions;
import com.netease.nim.uikit.business.session.constant.Extras;
import com.netease.nim.uikit.business.session.fragment.MessageFragment;
import com.netease.nim.uikit.business.uinfo.UserInfoHelper;
import com.netease.nim.uikit.common.activity.ToolBarOptions;
import com.netease.nim.uikit.common.adapter.BaseAdapter;
import com.netease.nim.uikit.impl.NimUIKitImpl;
import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.entity.KeFuEntity;
import com.netease.nim.uikit.net.entity.VideoGiftBean;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.CustomNotification;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.RxDeviceTool;
import com.vondear.rxtool.view.RxToast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import okhttp3.MediaType;
import okhttp3.RequestBody;


/**
 * 点对点聊天界面
 * <p/>
 * Created by huangjun on 2015/2/1.
 */
public class P2PMessageActivity extends BaseMessageActivity {

    private boolean isResume = false;
    private ImageView back;
    private TextView title;
    private ImageView personInfo;

    public static void start(Context context, String contactId, SessionCustomization customization, IMMessage anchor) {
        Intent intent = new Intent();
        intent.putExtra(Extras.EXTRA_ACCOUNT, contactId);
        intent.putExtra(Extras.EXTRA_CUSTOMIZATION, customization);
        intent.putExtra("", P2PMessageActivity.class);
        if (anchor != null) {
            intent.putExtra(Extras.EXTRA_ANCHOR, anchor);
        }
        intent.setClass(context, P2PMessageActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        context.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        View rl_center = findViewById(R.id.rl_center);
//        com.netease.nim.uikit.net.StatusBarUtil.setColor(this,getResources().getColor(R.color.white),0);
//        com.netease.nim.uikit.net.StatusBarUtil.setTranslucentForImageViewInFragment(this,0,rl_center);
//        com.netease.nim.uikit.net.StatusBarUtil.setLightMode(this);
//        StatusBarUtil.setStatusBarMode(this, true, R.color.white);

        back = findView(R.id.iv_return);
        personInfo = findView(R.id.iv_person);
        title = findView(R.id.title);
        // 单聊特例话数据，包括个人信息，
        requestBuddyInfo();
        displayOnlineState();
        registerObservers(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        registerObservers(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isResume = true;
        //判断是否是好友，还有是否拉黑
        judgeMemberRelation();
    }

    private String sfgz;
    private String sfhmd;

    private void judgeMemberRelation() {
        SubscriberOnNextListener<BaseBean<Map<String, String>>> onNextListener = baseBean -> {
            sfgz = baseBean.getData().get("sfgz");
            sfhmd = baseBean.getData().get("sfhmd");
        };
        Map<String, Object> dtModel = new HashMap<>();//登录上传参数
        dtModel.put("memberId", SharedHelper.readId(this));
        dtModel.put("otherMemberId", sessionId);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(dtModel));
        HttpMethods.getInstance().judgeMemberRelation(new ProgressSubscriber<>(onNextListener, this, false), requestBody);
    }

    @Override
    protected void onStop() {
        super.onStop();
        isResume = false;
    }

    private void requestBuddyInfo() {
        getToolBar().setVisibility(View.GONE);
//        setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
//        setTitle("");
        title.setText(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        personInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initPopup();

            }
        });
    }

    private void displayOnlineState() {
        if (!NimUIKitImpl.enableOnlineState()) {
            return;
        }
        String detailContent = NimUIKitImpl.getOnlineStateContentProvider().getDetailDisplay(sessionId);
        setSubTitle(detailContent);
    }


    /**
     * 命令消息接收观察者
     */
    private Observer<CustomNotification> commandObserver = new Observer<CustomNotification>() {
        @Override
        public void onEvent(CustomNotification message) {
            if (!sessionId.equals(message.getSessionId()) || message.getSessionType() != SessionTypeEnum.P2P) {
                return;
            }
            showCommandMessage(message);
        }
    };


    /**
     * 用户信息变更观察者
     */
    private UserInfoObserver userInfoObserver = new UserInfoObserver() {
        @Override
        public void onUserInfoChanged(List<String> accounts) {
            if (!accounts.contains(sessionId)) {
                return;
            }
            requestBuddyInfo();
        }
    };

    /**
     * 好友资料变更（eg:关系）
     */
    private ContactChangedObserver friendDataChangedObserver = new ContactChangedObserver() {
        @Override
        public void onAddedOrUpdatedFriends(List<String> accounts) {
            setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
        }

        @Override
        public void onDeletedFriends(List<String> accounts) {
            setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
        }

        @Override
        public void onAddUserToBlackList(List<String> account) {
            setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
        }

        @Override
        public void onRemoveUserFromBlackList(List<String> account) {
            setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
        }
    };

    /**
     * 好友在线状态观察者
     */
    private OnlineStateChangeObserver onlineStateChangeObserver = new OnlineStateChangeObserver() {
        @Override
        public void onlineStateChange(Set<String> accounts) {
            if (!accounts.contains(sessionId)) {
                return;
            }
            // 按照交互来展示
            displayOnlineState();
        }
    };

    private void registerObservers(boolean register) {
        NIMClient.getService(MsgServiceObserve.class).observeCustomNotification(commandObserver, register);
        NimUIKit.getUserInfoObservable().registerObserver(userInfoObserver, register);
        NimUIKit.getContactChangedObservable().registerObserver(friendDataChangedObserver, register);
        if (NimUIKit.enableOnlineState()) {
            NimUIKit.getOnlineStateChangeObservable().registerOnlineStateChangeListeners(onlineStateChangeObserver, register);
        }
    }


    protected void showCommandMessage(CustomNotification message) {
        if (!isResume) {
            return;
        }
        String content = message.getContent();
        try {
            JSONObject json = JSON.parseObject(content);
            int id = json.getIntValue("id");
            if (id == 1) {
                // 正在输入
                ToastHelper.showToastLong(P2PMessageActivity.this, "对方正在输入...");
            } else {
                ToastHelper.showToast(P2PMessageActivity.this, "command: " + content);
            }
        } catch (Exception ignored) {

        }
    }

    private MessageFragment fragment;
    @Override
    protected MessageFragment fragment() {
        Bundle arguments = getIntent().getExtras();
        arguments.putSerializable(Extras.EXTRA_TYPE, SessionTypeEnum.P2P);
        fragment = new MessageFragment();
        fragment.setArguments(arguments);
        fragment.setContainerId(R.id.message_fragment_container);
        return fragment;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.nim_message_activity;
    }

    @Override
    protected void initToolBar() {
        ToolBarOptions options = new NimToolBarOptions();
        setToolBar(R.id.toolbar, options);
    }

    @Override
    protected boolean enableSensor() {
        return true;
    }


    private void initPopup() {
        View view = View.inflate(this, R.layout.dialog_chat_person_operation, null);
        PopupWindow popupWindow;
        popupWindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        popupWindow.setContentView(view);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(null);
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);

        ArrayList<String> list = new ArrayList<>();
        if ("0".equals(sfgz)) {
            list.add("关注好友");
        } else {
            list.add("取消关注");
        }
        list.add("查看资料");
        list.add("清除聊天记录");
        if ("0".equals(sfhmd)) {
            list.add("拉黑");
        } else {
            list.add("移除黑名单");
        }
        list.add("举报");
        list.add("取消");

        RecyclerView rv = view.findViewById(R.id.rv);
        rv.setLayoutManager(new LinearLayoutManager(this));
        BaseQuickAdapter<String, BaseViewHolder> adapter = new BaseQuickAdapter<String, BaseViewHolder>
                (R.layout.item_chat_person_operation, list) {
            @Override
            protected void convert(BaseViewHolder helper, String item) {
                TextView content = helper.getView(R.id.tv);
                content.setText(item);
            }
        };
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String s = list.get(position);
                if (s.equals("关注好友") || s.equals("取消关注")) {
                    httpGz();
                } else if (s.equals("查看资料")) {
                    NimUIKitImpl.getSessionListener().checkMemberInfo(P2PMessageActivity.this, sessionId);
                } else if (s.equals("清除聊天记录")) {
                    //清除聊天记录
                    NIMClient.getService(MsgService.class).clearChattingHistory(sessionId, SessionTypeEnum.P2P);
                    RxToast.normal("清除成功！");
                    fragment.clearMessage();
                } else if (s.equals("拉黑") || s.equals("移除黑名单")) {
                    httpHeiMingDan();
                    //TODO
                } else if (s.equals("举报")) {
                    NimUIKitImpl.getSessionListener().juBao(P2PMessageActivity.this, sessionId);
                }
                popupWindow.dismiss();
            }
        });
        rv.setAdapter(adapter);
    }


    private void httpGz() {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            RxToast.normal(baseBean.getMsg());
            judgeMemberRelation();
        };
        Map<String, Object> userModel = new HashMap<>();
        userModel.put("gzrId", SharedHelper.readId(this));
        userModel.put("bgzId", sessionId);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(userModel));
        HttpMethods.getInstance().saveGuanZhu(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }

    private void httpHeiMingDan() {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            RxToast.normal(baseBean.getMsg());
            judgeMemberRelation();
        };
        Map<String, Object> userModel = new HashMap<>();
        userModel.put("memberId", SharedHelper.readId(this));
        userModel.put("otherMemberId", sessionId);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(userModel));
        HttpMethods.getInstance().saveHeiMingDan(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }
}
